package com.ozo.boot.common.core.exception.constant;

import com.ozo.boot.common.base.exception.AbstractExceptionEnum;
import com.ozo.boot.common.core.exception.annotation.ExceptionEnum;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;

/**
 * 异常枚举code值快速创建
 *
 * @author qiangesoft
 * @date 2024-06-28
 */
@Component
public class ExceptionEnumFactory implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<String> codes = new ArrayList<>();
        Class<?>[] classes = AbstractExceptionEnum.class.getClasses();
        for (Class<?> clazz : classes) {
            ExceptionEnum exceptionEnum = clazz.getAnnotation(ExceptionEnum.class);
            if (exceptionEnum != null) {
                String code = String.valueOf(exceptionEnum.module()) + exceptionEnum.category();
                if (codes.contains(code)) {
                    Assert.isTrue(true, exceptionEnum.getClass().getName() + "module,category repeat !");
                }
                codes.add(code);
            }
        }
    }

    /**
     * 获取异常枚举值code
     *
     * @param clazz
     * @param code
     * @return
     */
    public static Integer getExceptionCode(Class<?> clazz, int code) {
        // 默认的异常响应码
        Integer defaultCode = Integer.valueOf(ExceptionEnumModuleConstant.MODULE_SYS + ExceptionEnumCategoryConstant.AUTH_EXCEPTION_ENUM + "0");

        if (clazz == null) {
            return defaultCode;
        } else {
            ExceptionEnum exceptionEnum = clazz.getAnnotation(ExceptionEnum.class);
            if (exceptionEnum == null) {
                return defaultCode;
            }
            return Integer.valueOf("" + exceptionEnum.module() + exceptionEnum.category() + code);
        }
    }

}
